﻿Imports System.IO.Ports
'*** EXEMPO DA MICROSOFT ******************************************************
' http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.open.aspx#Y912
'******************************************************************************

Public Class Form1


    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim Portas As String() = SerialPort.GetPortNames()
        Dim todasportas As String = ""

        Console.Write("Portas encontradas:")
        For x As Integer = 0 To Portas.Count - 1
            todasportas = Portas(x) & " " & todasportas
        Next
        MsgBox("Portas encontradas: " & todasportas)
    End Sub

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        'Dim Com1A As New SerialPort

        '** Abrir a porta *****************************************************
        If Com1.IsOpen Then Com1.Close()

        Com1.PortName = "COM1"
        Com1.BaudRate = "1200"
        Com1.Parity = Parity.None
        Com1.DataBits = 8
        Com1.StopBits = StopBits.One

        Com1.Open()
        TextBox1.Text = TextBox1.Text & "Porta COM1 aberta." & vbCrLf
        System.Windows.Forms.Application.DoEvents()
        Com1.Write("X")

        ''** Envia dados para a porta ******************************************
        'Com1.Write("ATV1Q0" & Chr(13))
        'TextBox1.Text = TextBox1.Text & "Mensagem enviada ao destinatário" & vbCrLf
        'TextBox1.Text = TextBox1.Text & "Espenrando resposta de OK..." & vbCrLf

        ''** Recebe dados da porta *********************************************
        'Dim Buffer As String = ""
        'Do
        '    Buffer = Buffer & Com1.ReadExisting
        '    System.Windows.Forms.Application.DoEvents()
        'Loop Until InStr(Buffer, "OK" & vbCr)
        'TextBox1.Text = TextBox1.Text & "OK recebido com sucesso"

        ''** Fechar a porta ****************************************************

        'Com1.Close()

    End Sub

    Private Sub SerialPort1_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles Com1.DataReceived

        MsgBox(Com1.ReadExisting)
    End Sub
End Class
